﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AoYing_DeviceCollection
{
    public partial class FCTDeviceCollectionForm : Form
    { 
        public FCTDeviceCollectionForm()
        {
            InitializeComponent();
            BaseUtils._eventMsg.InfoHandler += EventMsg_Info;
            BaseUtils._eventMsg.ErrorMsgHandler += EventMsg_Error;
            BaseUtils._eventMsg.LogProcess = "锦飞";

            CheckForIllegalCrossThreadCalls = false; // 解除非窗口线程操作控件的限制
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //主板SN
            string maninSn = textBox1.Text;
            string linkSn = textBox2.Text;
            string messreturn = SmtMachine_Gather.FCT_GatherSmtMachine(maninSn, linkSn, comboBox1.Text);

            if (messreturn != "执行成功")
            {
                MessageBox.Show(messreturn);
            }
            textBox1.Clear();
            textBox2.Clear();
            textBox1.Focus();

        }
        #region ListBox信息填充
        private void EventMsg_Error(object sender, EventArgs e)
        {
            try
            {
                if (LB_Error.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                    }));
                }
                else
                {
                    WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理失败提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        private void EventMsg_Info(object sender, EventArgs e)
        {
            try
            {
                if (LB_Success.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Success, BaseUtils._eventMsg.Info);
                    }));
                }
                else
                {
                    WriteListBox(LB_Success, BaseUtils._eventMsg.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理成功提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 写提示信息，同样信息不会重复生成
        /// </summary>
        /// <param name="listBox"></param>
        /// <param name="message"></param>
        private void WriteListBox(ListBox listBox, string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            if (listBox.Items.Count < 1)
            {
                listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
                if (listBox.Name.Contains("Error"))
                {
                    new LogHelper().Error(message);

                }
                else
                {
                    new LogHelper().Info(message);

                }
                return;
            }
            var lastMessage = listBox.Items[0].ToString();
            if (lastMessage.Contains(message))
            {
                return;
            }

            listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
            if (listBox.Name.Contains("Error"))
            {
                new LogHelper().Error(message);
            }
            else
            {
                new LogHelper().Info(message);
            }
        }
        #endregion

        #region 页面加载动作
        private void Form1_Load(object sender, EventArgs e)
        {

            try
            {
                // 绑定 KeyDown 事件
                textBox1.KeyDown += textBox1_KeyDown;
                textBox2.KeyDown += textBox2_KeyDown;
                #region 设备下拉框绑定


                DataTable devicInfoDt = CommonHelper.GetDataTable($"select DeviceId from  deviceparameter where DeviceType='金凯博KC2700_xf';");

                // 清空ComboBox中的旧数据
                comboBox1.Items.Clear();

                // 确保DataTable中有数据后再进行绑定
                if (devicInfoDt.Rows.Count > 0)
                {
                    // 遍历DataTable并将DeviceId添加到ComboBox
                    foreach (DataRow row in devicInfoDt.Rows)
                    {
                        comboBox1.Items.Add(row["DeviceId"].ToString());
                    }

                    // 可选：设置ComboBox默认选中第一项
                    comboBox1.SelectedIndex = 0;
                }
                else
                {
                    MessageBox.Show("未找到相关设备信息！");
                }

                // 窗体加载时，默认选中textBox1
                BeginInvoke((MethodInvoker)delegate
                {
                    textBox1.Focus();
                });
                #endregion

            }
            catch (Exception ex)
            {
                BaseUtils._eventMsg.ErrorMsg = "锦飞采集Form加载异常" + ex.Message;
                MessageBox.Show("锦飞采集Form加载异常" + ex.Message);

            }
        }

        // 在TextBox1按下回车时，跳转到TextBox2
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下了回车键
            if (e.KeyCode == Keys.Enter)
            {
                // 移动焦点到TextBox2
                textBox2.Focus();
            }
        }
        // 在TextBox1按下回车时，跳转到TextBox2
        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下了回车键
            if (e.KeyCode == Keys.Enter)
            {
                button1.PerformClick();
            }
        }

        /// <summary>
        /// 页面关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FCTDeviceCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }
        #endregion

    }
}
